package com.zzyl.serve.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.bean.BeanUtils;
import com.zzyl.serve.domain.*;
import com.zzyl.serve.dto.CheckInApplyDto;
import com.zzyl.serve.dto.ElderFamilyDto;
import com.zzyl.serve.mapper.*;
import com.zzyl.serve.service.ICheckInService;
import com.zzyl.serve.util.CodeGenerator;
import com.zzyl.serve.vo.CheckInConfigVo;
import com.zzyl.serve.vo.CheckInDetailVo;
import com.zzyl.serve.vo.CheckInElderVo;
import com.zzyl.serve.vo.ElderFamilyVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * 入住Service业务层处理
 * 
 * @author liuyp
 * @date 2025-08-15
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;

    @Override
    public CheckInDetailVo detail(Long id) {
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        //根据id查询入住信息
        CheckIn checkIn = getById(id);
        //查询老人信息
        Elder elder = elderMapper.selectElderById(checkIn.getElderId());
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        BeanUtils.copyProperties(elder,checkInElderVo);
        //String类型转localdate类型
        checkInElderVo.setAge(LocalDate.now().getYear()-LocalDate.parse(elder.getBirthday()).getYear());
        checkInDetailVo.setCheckInElderVo(checkInElderVo);
        //老人家属信息
        List<ElderFamilyVo> elderFamilyVoList = JSONUtil.toList(elder.getRemark(),ElderFamilyVo.class);
        checkInDetailVo.setElderFamilyVoList(elderFamilyVoList);

        //根据入住id查询入住配置信息
        CheckInConfig checkInConfig = checkInConfigMapper.selectCheckInConfigByElderId(checkIn.getId());
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        BeanUtils.copyProperties(checkInConfig,checkInConfigVo);
        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());
        checkInConfigVo.setBedNumber(elder.getBedNumber());
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        //根据老人id查询合同
        Contract contract = contractMapper.selectContractByElderId(elder.getId());
        checkInDetailVo.setContract(contract);
        return checkInDetailVo;
    }

    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return checkInMapper.selectById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return checkInMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return checkInMapper.deleteById(id);
    }

    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;
    @Autowired
    private ContractMapper contractMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void apply(CheckInApplyDto dto) {
        //1. 判断老人是否存在且是“在住”状态：如果是，直接结束
        //  1.1 根据参数里的身份证号查询老人信息
        LambdaQueryWrapper<Elder> elderWrapper = Wrappers.<Elder>lambdaQuery()
                .eq(Elder::getIdCardNo, dto.getCheckInElderDto().getIdCardNo());
        Elder elder = elderMapper.selectOne(elderWrapper);
        //  1.2 如果查到了，并且这个老人的状态status是1，就说明老人是“在住”状态
        if (elder != null && Objects.equals(elder.getStatus(), 1)) {
            throw new BaseException("老人已在住，不能重复申请入住");
        }

        //2. 更新床位的状态为“已入住”
        //  2.1 根据床位id查询床位信息
        Bed bed = bedMapper.selectById(dto.getCheckInConfigDto().getBedId());
        //  2.2 如果此床位状态是“已入住”，则直接抛异常
        if (Objects.equals(bed.getBedStatus(), 1)) {
            throw new BaseException("此床位已入住");
        }
        //  2.3 将此床位状态更新为“已入住”
        bed.setBedStatus(1);
        bedMapper.updateById(bed);

        //3. 保存老人信息（新增或更新）
        //  3.1 将客户端提交的老人信息封装成Elder对象
        Elder newElder = new Elder();
        BeanUtils.copyProperties(dto.getCheckInElderDto(), newElder);
        newElder.setStatus(1);
        newElder.setBedId(bed.getId());
        newElder.setBedNumber(bed.getBedNumber());
        List<ElderFamilyDto> familyDtoList = dto.getElderFamilyDtoList();
        //将familyDtoList转换成json格式的字符串
        newElder.setRemark(JSONUtil.toJsonStr(familyDtoList));
        //  3.2 判断要新增或修改
        if (elder == null) {
            //如果刚才查询的老人信息为空，要新增
            elderMapper.insert(newElder);
        }else{
            //要修改
            newElder.setId(elder.getId());
            elderMapper.updateById(newElder);
        }

        //4. 新增入住信息
        //  4.1 封装CheckIn对象
        CheckIn checkIn = new CheckIn();
        checkIn.setElderName(dto.getCheckInElderDto().getName());
        checkIn.setElderId(newElder.getId());
        checkIn.setIdCardNo(dto.getCheckInElderDto().getIdCardNo());
        checkIn.setStartDate(dto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(dto.getCheckInConfigDto().getEndDate());
        checkIn.setNursingLevelName(dto.getCheckInConfigDto().getNursingLevelName());
        checkIn.setBedNumber(bed.getBedNumber());
        checkIn.setStatus(0);
        //  4.2 保存到check_in表里
        save(checkIn);

        //5. 新增入住配置
        //  5.1 封装CheckInConfig对象
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(dto.getCheckInConfigDto(), checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());
        //  5.2 保存到数据库表里
        checkInConfigMapper.insert(checkInConfig);

        //6. 保存合同信息
        //  6.1 封装Contract对象
        Contract contract = new Contract();
        BeanUtils.copyProperties(dto.getCheckInContractDto(), contract);
        contract.setElderId(newElder.getId());
        contract.setElderName(newElder.getName());
        contract.setContractNumber(CodeGenerator.generateContractNumber());
        contract.setStartDate(dto.getCheckInConfigDto().getStartDate());
        contract.setEndDate(dto.getCheckInConfigDto().getEndDate());
        //  合同状态是否生效 如果当前早于开始时间 或者 晚于结束时间，是无效的
        LocalDateTime now = LocalDateTime.now();
        boolean beNotInForce = now.isBefore(contract.getStartDate()) || now.isAfter(contract.getEndDate());
        contract.setStatus(beNotInForce?0:1);
        //  6.2 保存到数据库表里
        contractMapper.insert(contract);
    }
}
